package com.qyhl.module_home.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.snackbar.Snackbar;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.DownloadProgressCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.config.AppConfigBean;
import com.qyhl.webtv.commonlib.entity.news.AdvertiseBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;

import java.io.File;

import butterknife.BindView;

/**
 * 启动页
 */
@Route(path = ARouterPathConstant.MAIN)
public class MainActivity extends BaseActivity implements MainContract.MainView {
    private static final String TAG = MainActivity.class.getSimpleName();
    //启动图倒计时
    private static final long picCountDownTime = 2000;

    private long countDownTime;

    @BindView(R2.id.adv_cover)
    ImageView advCover;
    @BindView(R2.id.arrow)
    ImageView arrow;
    @BindView(R2.id.adv_title)
    TextView advTitle;
    @BindView(R2.id.adv_title_layout)
    RelativeLayout advTitleLayout;
    @BindView(R2.id.adv_tag_txt)
    TextView advTagTxt;
    @BindView(R2.id.skip_btn)
    TextView skipBtn;
    @BindView(R2.id.loading_mask)
    LoadingLayout loadingMask;
    @BindView(R2.id.adv_layout)
    RelativeLayout advLayout;
    @BindView(R2.id.boot_screen_cover)
    ImageView bootScreen;

    private MainPresenter mainPresenter;
    private LoadingDialog.Builder mBuilder;
    private CountDownTimer mCountDownTimer;
    private final static String PATH = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Adv;//图片下载文件夹
    private AppConfigBean.startAdvNew mBean;

    private int position;


    @Override
    protected int getContentView() {
        if (DateUtils.isSpecialDay() && CommonUtils.getInstance().getSite() == 140) {
            /*
             *  APP整体改为灰色
             */
            Paint mPaint = new Paint();
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);
            mPaint.setColorFilter(new ColorMatrixColorFilter(cm));
            getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE, mPaint);
        }
        return R.layout.home_activity_main;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar
                .fullScreen(true)
                .statusBarDarkFont(false)
                .navigationBarColor(R.color.transparent)
                .init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mainPresenter = new MainPresenter(this);
        loadingMask.setStatus(LoadingLayout.Success);
    }

    @Override
    protected void setListener() {
        setListeners();
        mainPresenter.getConfig();//请求配置信息
        mainPresenter.compareToken();
    }

    /**
     * 设置控件监听
     */
    private void setListeners() {
        //点击跳过监听
        skipBtn.setOnClickListener(v -> {
            if (mCountDownTimer != null) {
                mCountDownTimer.cancel();
            }
            RouterManager.router(ARouterPathConstant.HOME_ACTIVITY);
            finish();
        });

        //多状态布局监听  重载布局监听
        loadingMask.setOnReloadListener(v -> {
            if (NetUtil.isNetworkAvalible(MainActivity.this)) {
                mainPresenter.getConfig();
                mBuilder = new LoadingDialog.Builder(MainActivity.this);
                mBuilder.setTitle("获取中...").show();
            } else {
                Snackbar.make(loadingMask, "当前没有可以使用的网络，请设置网络！", Snackbar.LENGTH_INDEFINITE).setAction("设置", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivityForResult(new Intent(
                                        android.provider.Settings.ACTION_WIFI_SETTINGS),
                                0);
                    }
                }).show();
            }
        });


    }

    /**
     * 重新获取配置信息
     */
    @Override
    public void regainConfig() {
        loadingMask.setStatus(LoadingLayout.Success);
        if (mBuilder != null) {
            mBuilder.dismiss();
        }
        loadingMask.setErrorText("配置信息获取失败，点击重新获取...");
        loadingMask.setStatus(LoadingLayout.Error);
    }

    /**
     * 成功加载配置信息
     */
    @Override
    public void successConfig(AppConfigBean bean) {
        dismissLoading();
        RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutParam.setMargins(0, 0, 0, 270);
        if (StringUtils.isEmpty(bean.getAdvStyle()) || "0".equals(bean.getAdvStyle())) {
            advLayout.setLayoutParams(layoutParam);
            advTagTxt.setVisibility(View.VISIBLE);
            Log.e("conf", "success1");
        } else {
            Log.e("conf", "success2");
            advTagTxt.setVisibility(View.GONE);
        }
        loadingMask.setStatus(com.weavey.loading.lib.LoadingLayout.Success);
        if (mBuilder != null) {
            mBuilder.dismiss();
        }

        if (bean.getStartAdvList() != null && bean.getStartAdvList().size() > 0
                && bean.getStartAdvList().get(0).getAdvertise() != null
                && bean.getStartAdvList().get(0).getAdvertise().size() > 0) {  //有启动广告
            skipBtn.setVisibility(View.VISIBLE);
            advLayout.setVisibility(View.VISIBLE);
            advCover.setVisibility(View.VISIBLE);

            position = SpfManager.getInstance(this).getInt("advPosition", 0);

            if (position >= bean.getStartAdvList().get(0).getAdvertise().size()) {
                position = 0;
            }
            String advUrl = bean.getStartAdvList().get(0).getAdvertise().get(position).getImageUrl();
            SpfManager.getInstance(this).putInt("advPosition", position + 1);

            mBean = bean.getStartAdvList().get(0);

            countDownTime = mBean.getDuration() * 1000;
            Glide.with(MainActivity.this)
                    .load(advUrl)
                    .into(advCover);

            skipBtn.setEnabled("1".equals(mBean.getJumpover()));

            advLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String url = mBean.getAdvertise().get(0).getLink();
                    String title = mBean.getName();
                    AdvertiseBean advertiseBean = mBean.getAdvertise().get(0);
                    if (StringUtils.isEmpty(url) && !advertiseBean.getLinkType().equals("1") && !advertiseBean.getLinkType().equals("2") && !advertiseBean.getLinkType().equals("3") && !advertiseBean.getLinkType().equals("4")
                    ) {
                        return;
                    }
                    RouterManager.router(ARouterPathConstant.HOME_ACTIVITY);
                    switch (advertiseBean.getLinkType()) {
                        case "1": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                        }
                        break;
                        case "2":
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT, bundle);
                            break;
                        case "3":
                            switch (advertiseBean.getContentType()) {
                                case "1": {
                                    Bundle bundle2 = new Bundle();
                                    bundle2.putString("id", advertiseBean.getLinkId());
                                    RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle2);
                                }
                                break;
                                case "2": {
                                    Bundle bundle2 = new Bundle();
                                    bundle2.putString("section", advertiseBean.getLinkId());
                                    RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle2);
                                }
                                break;
                                case "3":
                                    break;
                                case "4":
                                    break;
                                case "5": {
                                    Bundle bundle2 = new Bundle();
                                    bundle2.putString("id", advertiseBean.getLinkId());
                                    RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle2);
                                }
                                break;
                                case "8": {
//                                        Router.build("room_act")
//                                                .with("roomId", Integer.parseInt(advertiseBean.getLinkId()))
//                                                .go(MainActivity.this);

                                }
                                break;
                                case "101":
                                    Bundle bundle2 = new Bundle();
                                    bundle2.putString("id", advertiseBean.getLinkId());
                                    RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle2);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        case "4":
                            Bundle bundle2 = new Bundle();
                            bundle2.putString("actId", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.ACT_DETAILS, bundle2);
                            ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.STARTUPPAGE, ActionConstant.ACTIVITY_DETAIL);
                            break;
                        default:
                            if (StringUtils.isNotEmpty(url)) {

                                Bundle bundle3 = new Bundle();
                                bundle3.putString("url", url);
                                bundle3.putString("title", title);
                                bundle3.putString("id", mBean.getId() + "");
                                RouterManager.router(MainActivity.this, ARouterPathConstant.ADV, bundle3, 1);
                            }
                            break;

                    }

                    if (mCountDownTimer != null) {
                        mCountDownTimer.cancel();
                        finish();
                    }

                }
            });
            countDown(countDownTime);
        } else{
            goToMainActivity();
        }
    }

    /**
     * 开启倒计时
     *
     * @param time
     */
    private void countDown(long time) {
        mCountDownTimer = new CountDownTimer(time, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                try {
                    if ("1".equals(mBean.getJumpover())) {
                        skipBtn.setText(millisUntilFinished / 1000 + 1 + " 跳过");
                    } else {
                        skipBtn.setText(millisUntilFinished / 1000 + 1 + " s");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onFinish() {
                if (mBean != null && mBean.getJumpover() != null) {
                    if ("1".equals(mBean.getJumpover())) {
                        skipBtn.setText(1 + " 跳过");
                    } else {
                        skipBtn.setText(1 + " s");
                    }
                }
                RouterManager.router(ARouterPathConstant.HOME_ACTIVITY);
                finish();
                Log.e("mainAct", "倒计时结束");
            }
        }.start();
    }


    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("启动页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("启动页");
        MobclickAgent.onPause(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            advLayout.setVisibility(View.GONE);
            RouterManager.router(ARouterPathConstant.HOME_ACTIVITY);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

//    /**
//     * 加载开屏广告
//     */
//    private void loadSplashAd() {
//        //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
//        AdSlot adSlot = new AdSlot.Builder()
//                .setPtgSlotId(CommonUtils.getInstance().getPtgSplashId())
//                .setSupportDeepLink(true)
//                .setNeedSkipView(true)
//                .setAdContainer(advLayout)
//                .build();
//
//        PtgAdSdk.get().loadSplashAd(this, adSlot, new PtgAdNative.SplashAdListener() {
//            @Override
//            public void onError(AdError adError) {
//                goToMainActivity();
//            }
//
//            @Override
//            public void onTimeout() {
//                Log.e(TAG, "开屏请求超时");
//                goToMainActivity();
//            }
//
//            @Override
//            public void onSplashAdLoad(PtgSplashAd ad) {
//                Log.e(TAG, "开屏广告请求成功");
//                if (ad == null) {
//                    return;
//                }
//                advLayout.setVisibility(View.VISIBLE);
////                if (!MainActivity.this.isFinishing()) {
////
////                } else {
////                    goToMainActivity();
////                }
//                ad.setSplashInteractionListener(new PtgSplashAd.AdInteractionListener() {
//
//                    @Override
//                    public void onAdClicked() {
//
//                    }
//
//                    @Override
//                    public void onAdShow() {
//
//                    }
//
//                    /**
//                     * 点击跳过时回调
//                     */
//                    @Override
//                    public void onAdSkip() {
//                        goToMainActivity();
//
//                    }
//
//                    /**
//                     * 广告播放时间结束
//                     */
//                    @Override
//                    public void onAdTimeOver() {
//                        goToMainActivity();
//                    }
//                });
//            }
//        });
//
//    }
//
    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        RouterManager.router(ARouterPathConstant.HOME_ACTIVITY);
        finish();
    }
}
